package com.diaohaiwen.basic.account.impl;

import com.diaohaiwen.basic.account.mapper.AccountMapper;
import com.diaohaiwen.basic.account.obj.model.Account;
import com.diaohaiwen.basic.account.obj.model.table.AccountDef;
import com.diaohaiwen.basic.account.service.RegisterService;
import com.diaohaiwen.common.enums.StatusCodeEnum;
import com.diaohaiwen.common.exception.GlobalException;
import com.diaohaiwen.common.obj.bo.MD5CryptoBo;
import com.diaohaiwen.common.util.CryptoUtil;
import com.diaohaiwen.common.util.NumberUtil;
import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.function.Consumer;

/**
 * @author 刁海文
 * @Remark
 * @since 2023/7/22 15:29
 */
@Service
public class RegisterImpl implements RegisterService {

    @Resource
    AccountMapper accountMapper;


    @Override
    public Account register(Account account) {
        account.setId(null);
        // 属性校验
        validInfo(account.getUsername(), AccountDef.account.username);
        validInfo(account.getMobile(), AccountDef.account.mobile);
        validInfo(account.getEmail(), AccountDef.account.email);

        // 加密
        crypto(account::setSalt, account::setPasswd, account.getPasswd());

        accountMapper.insert(account);

        return account;
    }

    /**
     * 字段重复校验
     *
     * @param value  值
     * @param column 字段
     */
    private void validInfo(String value, QueryColumn column) {
        QueryWrapper wrapper = QueryWrapper.create().where(column.eq(value));
        long count = accountMapper.selectCountByQuery(wrapper);
        if (count > NumberUtil.INTEGER_ZERO) {
            throw new GlobalException(StatusCodeEnum.DATA.status, String.format("%s [%s] 重复", column.getName(), value));
        }
    }


    /**
     * 设置用户名密码
     *
     * @param salt   加密盐
     * @param passwd 密码
     * @param str    原密码
     */
    private void crypto(Consumer<String> salt, Consumer<String> passwd, String str) {
        MD5CryptoBo cryptoBo = CryptoUtil.md5(str);
        salt.accept(cryptoBo.getSalt());
        passwd.accept(cryptoBo.getPass());
    }


}
